package sg.edu.nus.iss.billing.template;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import sg.edu.nus.iss.billing.exception.TemplateEngineException;
import sg.edu.nus.iss.billing.template.interfaces.ParseAction;
import sg.edu.nus.iss.billing.template.interfaces.ParseActionProcessor;

/**
 * @author Daniel
 *
 */
public class FileOutputParseActionProcessor implements ParseActionProcessor {
	
	private File file;
	private ParseActionProcessor actionProcessor;
	
	public FileOutputParseActionProcessor(ParseActionProcessor processor, File file) {
		this.actionProcessor = processor;
		this.file = file;
	}
	
	public void addParseAction(ParseAction parseAction) {
		actionProcessor.addParseAction(parseAction);
	}
	public void addParseActionList(List<ParseAction> parseActionList) {
		actionProcessor.addParseActionList(parseActionList);
	}
	public String getParsedString() {
		return actionProcessor.getParsedString();
	}
	
	public void process() throws TemplateEngineException {
		actionProcessor.process();
		writeFile();
	}
	
	private void writeFile() throws TemplateEngineException {
		//File f = new File(this.outputFilePath + File.separatorChar + this.outputFileName);
		if (file.exists()) {
			return;
		}
		FileOutputStream os = null;
		PrintWriter pw = null;
		try {
			os = new FileOutputStream(file);
			pw = new PrintWriter(os);
			pw.println(actionProcessor.getParsedString());
			pw.flush();
		} catch (FileNotFoundException e) {
			throw new TemplateEngineException(e.getMessage());
		} finally {
			try {
				if (pw != null) pw.close();
				if (os != null) os.close();
			} catch (IOException e) {
				throw new TemplateEngineException(e.getMessage());
			}
		}
	}
	
	
	

}
